<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="合同名称">
              <a-input placeholder="请输入合同名称" v-model="queryParam.contractName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>

        <template slot="contractFiles" slot-scope="text">
          <a-button v-if="text" @click="preview(text)">下载合同</a-button>
        </template>
        <template slot="sealedContractAttachmentFiles" slot-scope="text">
          <a-button v-if="text" @click="preview(text)">下载合同</a-button>
        </template>
        <template slot="imgSlot" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            :preview="record.id"
            height="25px"
            alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a
            @click="
              () => {
                visible = true
                formData = Object.assign({}, record)
              }
            "
            >编辑</a
          >

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <!-- <gz-contract-info-modal ref="modalForm" @ok="modalFormOk"></gz-contract-info-modal> -->
    <a-modal
      :visible="visible"
      :width="500"
      title="编辑合同"
      :confirmLoading="submitLoad"
      destroyOnClose
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning">
        <a-form-model ref="ruleForm" :model="formData" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
          <a-form-model-item label="合同名称" prop="contractName">
            <a-input disabled v-model="formData.contractName" />
          </a-form-model-item>
          <a-form-model-item label="跟进人" prop="followUser">
            <a-input disabled v-model="formData.followUser" />
          </a-form-model-item>
          <a-form-model-item label="合同模板" prop="fileList">
            <div class="file_item">
              <span class="preview" style="line-height: 20px;" @click="preview(formData.contractFiles)">{{
                formData.contractFiles
              }}</span>
            </div>
          </a-form-model-item>
          <a-form-model-item label="盖章合同文件" prop="fileList">
            <a-upload
              v-if="!formData.sealedContractAttachmentFiles"
              ref="uploadRef"
              name="file"
              :action="actionUrl"
              :headers="{
                'X-Access-Token': $store.state.user.token
              }"
              @change="handleChange"
              :showUploadList="false"
            >
              <a-button> <a-icon type="upload" /> 文件上传 </a-button>
            </a-upload>
            <div v-else class="file_item">
              <span
                class="preview"
                style="line-height: 20px;"
                @click="preview(formData.sealedContractAttachmentFiles)"
                >{{ formData.sealedContractAttachmentFiles }}</span
              >
              <span @click="formData.sealedContractAttachmentFiles = undefined"
                ><a-icon style="color: red;cursor: pointer;" type="delete"
              /></span>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import GzContractInfoModal from './modules/GzContractInfoModal'
import { apiContractManageEdit } from '../../../api/contractManage/contractTemplate'

export default {
  name: 'GzContractInfoList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    GzContractInfoModal
  },
  data() {
    return {
      description: '合同管理管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '合同名称',
          align: 'center',
          dataIndex: 'contractName'
        },
        {
          title: '跟进业务员',
          align: 'center',
          dataIndex: 'followUser'
        },
        {
          title: '下载未盖章合同',
          align: 'center',
          dataIndex: 'contractFiles',
          scopedSlots: { customRender: 'contractFiles' }
        },
        {
          title: '下载已盖章合同',
          align: 'center',
          dataIndex: 'sealedContractAttachmentFiles',
          scopedSlots: { customRender: 'sealedContractAttachmentFiles' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/gzContractInfo/list',
        delete: '/gzContractInfo/delete',
        deleteBatch: '/gzContractInfo/deleteBatch',
        exportXlsUrl: '/gzContractInfo/exportXls',
        importExcelUrl: 'gzContractInfo/importExcel'
      },
      dictOptions: {},
      superFieldList: [],
      visible: false,
      formData: {},
      spinning: false,
      submitLoad: false
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    actionUrl() {
      return process.env.VUE_APP_API_BASE_URL + '/api/file/upload'
    }
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'number', text: '合同编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'contractName', text: '合同名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'type', text: '合同类型', dictCode: '' })
      fieldList.push({ type: 'string', value: 'agentName', text: '代理商名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'phone', text: '代理商电话', dictCode: '' })
      fieldList.push({ type: 'string', value: 'address', text: '代理商地址', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'content', text: '合同变更内容', dictCode: '' })
      fieldList.push({ type: 'date', value: 'signingDate', text: '合同签约时间' })
      fieldList.push({ type: 'string', value: 'followUser', text: '跟进业务员', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '审核状态', dictCode: '' })
      fieldList.push({ type: 'string', value: 'remarks', text: '备注', dictCode: '' })
      this.superFieldList = fieldList
    },
    // 文件上传
    handleChange({ file }) {
      this.spinning = true
      const { status, response } = file
      if (status === 'done') {
        const { code, result } = response
        this.spinning = false
        if (code === 0) {
          const { fileId, contractName: fileName, url } = result
          this.formData.sealedContractAttachmentFiles = url
        }
      }
    },
    async handleSubmit() {
      this.submitLoad = true
      const { code, message: msg } = await apiContractManageEdit(this.formData)
      this.submitLoad = false
      if (code === 200) {
        this.visible = false
        this.$message.success('操作成功！')
        this.searchQuery()
      } else {
        this.$message.error(msg)
      }
    },
    handleCancel() {
      this.visible = false
      this.formData = {}
    },
    preview(url) {
      window.open(url)
    },
    downloadFile(url, filename) {
      axios(url)
        .then(response => {
          console.log(response, 'aaaa')

          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.blob() // 将响应转换为Blob对象
        })
        .then(blob => {
          // 创建一个链接元素
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob) // 设置链接的href属性为Blob对象的URL
          link.download = filename // 设置下载的文件名
          document.body.appendChild(link) // 将链接添加到文档中
          link.click() // 触发点击事件以开始下载
          document.body.removeChild(link) // 下载后移除链接
          window.URL.revokeObjectURL(link.href) // 释放Blob URL
        })
        .catch(error => {
          console.error('下载文件时出错:', error)
        })
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
::v-deep {
  .ant-form-item-control {
    line-height: 10px;
  }
}
.preview:hover {
  color: #1890ff;
  cursor: pointer;
}
</style>
